from PySide6 import QtWidgets, QtCore, QtGui
from .editorwidget import EditorMainWindow

class MainWindow(QtWidgets.QMainWindow):
    
    def __init__(self):
        super(MainWindow, self).__init__()

        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setObjectName("MainWindow")
        # 初始化窗口调整相关变量
        self.dragging = False
        self.resizing = False
        self.drag_position = QtCore.QPoint()
        self.resize_direction = None
        
        # 设置边缘检测阈值（像素）
        self.edge_threshold = 8

        self._titlebarwidget = QtWidgets.QWidget()
        self._titlebarwidget.setFixedHeight(30)
        self._titlebarwidget.setObjectName("TitleBarWidget")
        self._centerWidget = QtWidgets.QWidget()
        self._centerWidget.setObjectName("MainWindowCenterWidget")
        self.setCentralWidget(self._centerWidget)
        mainlayout = QtWidgets.QVBoxLayout()
        mainlayout.setContentsMargins(0, 0, 0, 0)
        mainlayout.setSpacing(0)
        layout = QtWidgets.QHBoxLayout()
        mainlayout.addWidget(self._titlebarwidget)
        mainlayout.addLayout(layout)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        self._centerWidget.setLayout(mainlayout)
        self._leftCtrlWidget = QtWidgets.QWidget()
        self._leftCtrlWidget.setLayout(QtWidgets.QVBoxLayout())
        self._leftCtrlWidget.layout().setSpacing(20)
        self._leftCtrlWidget.layout().addStretch()
        self._leftCtrlWidget.setFixedWidth(50)
        self._leftCtrlWidget.setObjectName("SideBar")
        self._leftCtrlWidget.setStyleSheet("""
QWidget#SideBar{
    border-right: 1px solid #393939;
}
""")

        self._displayWidget = QtWidgets.QWidget()
        self._displayWidget.setObjectName("DisplayWidget")
        self._displayWidget.setLayout(QtWidgets.QVBoxLayout())
        layout.addWidget(self._leftCtrlWidget)
        layout.addWidget(self._displayWidget)

        self.InitSideBarButton()
        self.InitTitleBar()
        self.InitMenuBar()
        self.InitDisplayArea()

    def InitDisplayArea(self):
        self._displayWidget.layout().setContentsMargins(0, 0, 0, 0)

        self._flowEditor = EditorMainWindow()
        self._displayWidget.layout().addWidget(self._flowEditor)


    def InitTitleBar(self):
        layout = QtWidgets.QHBoxLayout()
        layout.setContentsMargins(10, 0, 0, 0)
        layout.setSpacing(0)
        self._titlebarwidget.setLayout(layout)
        self._titlebarwidget.layout().addStretch()
        self._icon = QtWidgets.QLabel("")
        self._icon.setPixmap(QtGui.QPixmap("./res/icon.png"))
        self._icon.setFixedSize(19, 19)
        self._icon.setScaledContents(True)

        self._splitwidget = QtWidgets.QWidget()
        self._splitwidget.setFixedWidth(30)

        self._menubar = QtWidgets.QMenuBar()
        self._menubar.setObjectName("MainMenuBar")
        self._menubar.setFixedHeight(24)
        self._closeBtn = QtWidgets.QToolButton()
        self._closeBtn.setText("")
        self._closeBtn.setAutoRaise(True)
        self._closeBtn.setIcon(QtGui.QIcon(QtGui.QPixmap("./res/close.png")))
        self._closeBtn.setFixedSize(44, 22)
        
        self._maximumBtn = QtWidgets.QToolButton()
        self._maximumBtn.setText("")
        self._maximumBtn.setAutoRaise(True)
        self._maximumBtn.setIcon(QtGui.QIcon(QtGui.QPixmap("./res/maximum.png")))
        self._maximumBtn.setFixedSize(44, 22)
        
        self._minimumBtn = QtWidgets.QToolButton()
        self._minimumBtn.setText("")
        self._minimumBtn.setAutoRaise(True)
        self._minimumBtn.setIcon(QtGui.QIcon(QtGui.QPixmap("./res/minimum.png")))
        self._minimumBtn.setFixedSize(44, 22)

        layout.addWidget(self._minimumBtn)
        layout.addWidget(self._maximumBtn)
        layout.addWidget(self._closeBtn)

        layout.insertWidget(0, self._icon)
        layout.insertWidget(1, self._splitwidget)
        layout.insertWidget(2, self._menubar)

        self._closeBtn.clicked.connect(self.onTriggerClose)
        self._minimumBtn.clicked.connect(self.onTriggerMinimun)
        self._maximumBtn.clicked.connect(self.onTriggerMaximum)

    def InitSideBarButton(self):
        self._flowBtn = QtWidgets.QToolButton()
        self._flowBtn.setText("Flows")
        self._flowBtn.setFixedSize(31, 31)
        self._flowBtn.setIconSize(QtCore.QSize(31, 31))
        self._flowBtn.setAutoRaise(True)
        self._flowBtn.setIcon(QtGui.QIcon(QtGui.QPixmap("./res/flow.png")))

        self._actBtn = QtWidgets.QToolButton()
        self._actBtn.setText("Actions")
        self._actBtn.setFixedSize(31, 31)
        self._actBtn.setIconSize(QtCore.QSize(31, 31))
        self._actBtn.setAutoRaise(True)
        self._actBtn.setIcon(QtGui.QIcon(QtGui.QPixmap("./res/action.png")))
        
        self._settingsBtn = QtWidgets.QToolButton()
        self._settingsBtn.setText("Settings")
        self._settingsBtn.setFixedSize(31, 31)
        self._settingsBtn.setIconSize(QtCore.QSize(31, 31))
        self._settingsBtn.setAutoRaise(True)
        self._settingsBtn.setIcon(QtGui.QIcon(QtGui.QPixmap("./res/settings.png")))

        self._leftCtrlWidget.layout().insertWidget(0, self._flowBtn)
        self._leftCtrlWidget.layout().insertWidget(1, self._actBtn)
        self._leftCtrlWidget.layout().addWidget(self._settingsBtn)

    def InitMenuBar(self):
        self._fileMenu = QtWidgets.QMenu("File")
        self._newFlowAction = QtWidgets.QAction("New &flow")
        self._newActionAction = QtWidgets.QAction("New &action")
        self._saveAction = QtWidgets.QAction("&Save")
        self._saveAllAction = QtWidgets.QAction("Save all")
        self._exitAction = QtWidgets.QAction("&Exit")
        self._fileMenu.addAction(self._newFlowAction)
        self._fileMenu.addAction(self._newActionAction)
        self._fileMenu.addSeparator()
        self._fileMenu.addAction(self._saveAction)
        self._fileMenu.addAction(self._saveAllAction)
        self._fileMenu.addSeparator()
        self._fileMenu.addAction(self._exitAction)

        self._editMenu = QtWidgets.QMenu("Edit")

        self._menubar.addMenu(self._fileMenu)
        self._menubar.addMenu(self._editMenu)

        self._menubar.triggered.connect(self.onTriggerMenu)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            # 检查是否点击了边缘区域
            self.resize_direction = self.get_resize_direction(event.pos())
            
            if self.resize_direction:
                self.resizing = True
                self.drag_position = event.globalPos()
            else:
                # 否则设为窗口移动模式
                self.dragging = True
                self.drag_position = event.globalPos() - self.frameGeometry().topLeft()
        super().mousePressEvent(event)
    
    def mouseMoveEvent(self, event):
        # 更新鼠标光标形状
        if not self.resizing and not self.dragging:
            direction = self.get_resize_direction(event.pos())
            cursor = self.get_cursor_for_direction(direction)
            if cursor:
                self.setCursor(cursor)
            else:
                self.unsetCursor()
        
        # 窗口调整大小逻辑
        if self.resizing:
            global_pos = event.globalPos()
            delta = global_pos - self.drag_position
            
            rect = self.geometry()
            screen_geo = QtWidgets.QApplication.primaryScreen().availableGeometry()
            min_width, min_height = 100, 80
            
            if self.resize_direction & QtCore.Qt.LeftEdge:
                new_left = rect.left() + delta.x()
                if new_left < rect.right() - min_width:
                    rect.setLeft(new_left)
                else:
                    rect.setLeft(rect.right() - min_width)
            
            if self.resize_direction & QtCore.Qt.TopEdge:
                new_top = rect.top() + delta.y()
                if new_top < rect.bottom() - min_height:
                    rect.setTop(new_top)
                else:
                    rect.setTop(rect.bottom() - min_height)
            
            if self.resize_direction & QtCore.Qt.RightEdge:
                rect.setRight(rect.right() + delta.x())
                if rect.width() < min_width:
                    rect.setWidth(min_width)
                if rect.right() > screen_geo.right():
                    rect.setRight(screen_geo.right())
            
            if self.resize_direction & QtCore.Qt.BottomEdge:
                rect.setBottom(rect.bottom() + delta.y())
                if rect.height() < min_height:
                    rect.setHeight(min_height)
                if rect.bottom() > screen_geo.bottom():
                    rect.setBottom(screen_geo.bottom())
            
            self.setGeometry(rect)
            self.drag_position = global_pos
        
        # 窗口移动逻辑
        elif self.dragging:
            move_to = event.globalPos() - self.drag_position
            self.move(move_to)
        
        super().mouseMoveEvent(event)
    
    def mouseReleaseEvent(self, event):
        self.dragging = False
        self.resizing = False
        self.unsetCursor()
        super().mouseReleaseEvent(event)
    
    def get_resize_direction(self, pos):
        """根据鼠标位置确定调整方向"""
        rect = self.rect()
        top = pos.y() < self.edge_threshold
        bottom = pos.y() > rect.height() - self.edge_threshold
        left = pos.x() < self.edge_threshold
        right = pos.x() > rect.width() - self.edge_threshold
        
        direction = None
        if top and left:
            direction = QtCore.Qt.TopEdge | QtCore.Qt.LeftEdge
        elif top and right:
            direction = QtCore.Qt.TopEdge | QtCore.Qt.RightEdge
        elif bottom and left:
            direction = QtCore.Qt.BottomEdge | QtCore.Qt.LeftEdge
        elif bottom and right:
            direction = QtCore.Qt.BottomEdge | QtCore.Qt.RightEdge
        elif top:
            direction = QtCore.Qt.TopEdge
        elif bottom:
            direction = QtCore.Qt.BottomEdge
        elif left:
            direction = QtCore.Qt.LeftEdge
        elif right:
            direction = QtCore.Qt.RightEdge
        
        return direction
    
    def get_cursor_for_direction(self, direction):
        """根据调整方向返回对应的光标"""
        if direction is None:
            return None
        
        if direction == (QtCore.Qt.LeftEdge | QtCore.Qt.TopEdge) or direction == (QtCore.Qt.RightEdge | QtCore.Qt.BottomEdge):
            return QtCore.QCursor(QtCore.Qt.SizeFDiagCursor)
        elif direction == (QtCore.Qt.RightEdge | QtCore.Qt.TopEdge) or direction == (QtCore.Qt.LeftEdge | QtCore.Qt.BottomEdge):
            return QtCore.QCursor(QtCore.Qt.SizeBDiagCursor)
        elif direction == QtCore.Qt.LeftEdge or direction == QtCore.Qt.RightEdge:
            return QtCore.QCursor(QtCore.Qt.SizeHorCursor)
        elif direction == QtCore.Qt.TopEdge or direction == QtCore.Qt.BottomEdge:
            return QtCore.QCursor(QtCore.Qt.SizeVerCursor)
        
        return None
    
    def update_cursor_shape(self, direction):
        """根据鼠标位置更新光标形状"""
        if direction is None:
            self.setCursor(Qt.ArrowCursor)
            return
        
        # 对角方向
        if direction == (QtCore.Qt.LeftEdge | QtCore.Qt.TopEdge) or direction == (QtCore.Qt.RightEdge | QtCore.Qt.BottomEdge):
            self.setCursor(QtCore.Qt.SizeFDiagCursor)
        elif direction == (QtCore.Qt.RightEdge | QtCore.Qt.TopEdge) or direction == (QtCore.Qt.LeftEdge | QtCore.Qt.BottomEdge):
            self.setCursor(QtCore.Qt.SizeBDiagCursor)
        
        # 水平边界
        elif direction == QtCore.Qt.LeftEdge or direction == QtCore.Qt.RightEdge:
            self.setCursor(QtCore.Qt.SizeHorCursor)
        
        # 垂直边界
        elif direction == QtCore.Qt.TopEdge or direction == QtCore.Qt.BottomEdge:
            self.setCursor(QtCore.Qt.SizeVerCursor)
        
        # 其他情况恢复默认
        else:
            self.setCursor(QtCore.Qt.ArrowCursor)
        
    def onTriggerClose(self):
        QtWidgets.QApplication.instance().exit(0)

    def onTriggerMinimun(self):
        self.showMinimized()
    
    def onTriggerMaximum(self):
        if self.isMaximized():
            self.showNormal()
        else:
            self.showMaximized()

    def onTriggerMenu(self, act):
        if act == self._saveAction:
            self._flowEditor.saveCurrentFlow()
        elif act == self._exitAction:
            self.onTriggerClose()

def Main():
    import sys
    qapp = QtWidgets.QApplication(sys.path[1:])
    w = MainWindow()
    w.resize(1024, 600)
    w.show()

    w.setStyleSheet("""
QDockWidget {
    background-color: #262626;
}
QWidget {
    background-color: #262626;
    color: #fffbb6;
    border: none;
}
QMenuBar {
    background-color: #262626;
    color: #fffbb6;
    border: none;
}
QMenuBar::item:pressed {
    background: #a0a0a0;
    color: white;
}
QMenuBar::item:selected {
    background: #a0a0a0;
    color: black;
}
QTabWidget::pane {
    border: none;
    margin: 0;
    padding: 0;
}
QTabBar::tab {
    background-color: #262626;
    color: #fffbb6;
    font-size: 11px;
    min-height: 36;
}
QTabBar::tab:selected {
    background-color: #595959;      /* 选中状态的背景色 */
    color: #d7cd0b;                   /* 选中状态的文字颜色 */
    border-color: #2980b9;
    font-size: 13px;
}
""")

    qapp.exec_()


if "__main__" == __name__:
    Main()
